var queryObj = getQuery()
console.log(queryObj, 'queryObj===')

var version = ''
var cid = ''
var device = ''
var network = ''

var CUR_SUCCESS_URL = '' // 当前IP

// 初始化获取app信息
function initParams() {
  zs.getNetworkStatus({
    success(res) {
      console.log('获取网络类型', res)
      if (res.status === 'wifi') {
        network = 'wifi'
      } else {
        network = 'mobile'
      }
    },
    fail(err) {
      console.log(err, '网络状态的回调')
    }
  })
  zs.getUserId({
    success(res) {
      console.log(res, 'res - getUserId')
      cid = res.clientId
    },
    fail(res) {
      console.log(res, 'err - getUserId')
    }
  })
  zs.getInfo({
    success(res) {
      console.log(res, 'res - getInfo')
      var data = res.ver.split(';')
      version = data[0]
      device = data[1]
    },
    fail(res) {
      console.log(res, 'err - getInfo')
    }
  })
}

initParams()

// 多个ip，取随机位置后，往后轮训请求，请求通一个则后续取消
// var urls = ['https://210.21.237.135', 'https://210.21.237.138', 'https://[240e:6b1:10:1::9]'] //测试ip
var urls = [
  'https://120.24.92.132:2443',
  'https://[2408:4003:108c:1e01:247:afbd:24da:8726]:2443',
  'https://47.94.220.89:2443',
  'https://[2408:400a:13d:1f07:9f7e:57e6:d9f0:7fc]:2443',
  'https://47.100.225.68:2443',
  'https://[2408:4002:1020:3400:b17c:a5f2:f15c:afbb]:2443',
  'https://42.193.148.188:2443',
  'https://[2402:4e00:1012:de00:0:9422:aec4:c870]:2443',
  'https://1.116.247.238:2443',
  'https://[2402:4e00:1402:8801:0:9424:31e1:e438]:2443',
  'https://49.232.75.55:2443',
  'https://[2402:4e00:1201:c700:0:9422:b141:6353]:2443'
]

function getRequestUrl(index) {
  return urls[index] + '/mo/api/check'
}

// 随机ip起始位置
var networkUrlIdx = Math.floor(Math.random() * urls.length)

// 超时时间统计
var dateTiem = 3

// ip数量*超时时间，超时时间长度
var timeoutDate = (urls.length - networkUrlIdx) * dateTiem

function netwrokFetch(params) {
  // 请求设置超时
  var overtimeTimer = null
  return new Promise(function(resolve, reject){
    zs.httpRequest({
      params,
      success(res) {
        overtimeTimer = clearInterval(overtimeTimer)
        resolve(res)
      },
      fail(err) {
        overtimeTimer = clearInterval(overtimeTimer)
        reject(err)
      }
    })
    // 超过三秒不接收数据
    overtimeTimer = setTimeout(function() {
      overtimeTimer = clearInterval(overtimeTimer)
      reject({ code: 20000 })
    }, dateTiem * 1000)
  })
}

function getNetwork(params, callback, errorBack) {
  var data = {
    checkVer: "1.0.0",
    checkRequest: {
      checkLevel: 0,
      channel: (queryObj && queryObj.channel) || 'default',
      clientInfo: {
        os: "22",
        version,
        cid,
        device,
        network,
        timestamp: new Date().getTime()
      }
    }
  }
  function pingNetworkItem() {
    var httpData = {
      url: CUR_SUCCESS_URL || getRequestUrl(networkUrlIdx),
      method: 'post',
      type: 'json',
      body: params || data,
    }
    console.log(httpData, 'httpData====params')

    netwrokFetch(httpData)
      .then(function(res) {
        console.log(res, networkUrlIdx, '获取网络策略成功')
        // params存在则代表是首次获取策略成功且循环检查策略成功（第二次策略
        if (params || (res.code === 0)) {
          // 首次请求param为undefind 如果获取成功则持续使用IP
          !params && (CUR_SUCCESS_URL = CUR_SUCCESS_URL || getRequestUrl(networkUrlIdx))
          // 当前检索的ip索引在返回时候必须要和最新的步骤索引一致
          callback && callback(res)
        } else if (!urls[networkUrlIdx + 1]) {
          // ip检索没了
          errorBack && errorBack(res)
        }
      })
      .catch(function(err) {
        console.log(err, 'err - 获取网络策略失败')
        // 超时处理及报错处理
        CUR_SUCCESS_URL = ''
        if (!params && urls[networkUrlIdx + 1]) {
          networkUrlIdx += 1
          getNetwork(params, callback, errorBack)
        } else {
          errorBack && errorBack(err)
        }
      })
  }
  pingNetworkItem()
}
